#coding:utf-8
'''
create on 2017-09-01
@author:sandy
'''

from pycommon import TBaseProtocol
from pycommon import Const
import ClientFactory
import ClientParse
import time
import logging

CLIENT_STATE_INIT               = 0
CLIENT_STATE_LOGINED            = 1
CLIENT_STATE_TO_CLOSE           = 2

class ClientSrv(TBaseProtocol.TBaseProtocol):

    def __init__(self,pid, addr):
        TBaseProtocol.TBaseProtocol.__init__(self)
        self.clientSocketType = Const.CLIENT_TCP_SOCKET
        self.__id = pid
        self.__addr = addr
        self.__ip = addr.host.decode('utf-8')
        self.state = CLIENT_STATE_INIT
        self.toclosetime = time.time()

        self.sid = 0
        self.sip = u''
        self.sport = 0

    def getId(self):
        return self.__id
    
    def getIp(self):
        return self.__ip

    def getState(self):
        return self.state

    def packetReceived(self, cmd, pkt):
        if self.state == CLIENT_STATE_TO_CLOSE:
            return
        try:
            ClientParse.parse(self, cmd, pkt)
        except Exception:
            logging.exception(u"Clientparse.parse(), cmd=%d" % cmd)

    def sendPacket(self, pkt):
        if not self.isConnected():
            logging.warn(u"sendPacket() not connected")
            return
        TBaseProtocol.TBaseProtocol.sendPacket(self, pkt)
    
    def connectionMade(self):
        logging.debug(u"ClientSrv.connectionMade() ip=%s", self.__ip) 
        TBaseProtocol.TBaseProtocol.reset(self)
   
    def connectionLost(self, reason):
        logging.debug(u"ClientSrv.connectionLost %s", reason)
        self.state = CLIENT_STATE_TO_CLOSE
        ClientFactory.instance.removeProtocol(self)

    def login(self,sid,ip,port):
        self.sid = sid
        self.sip = ip
        self.sport = port

    def getSId(self):
        return self.sid

    def getSIp(self):
        return self.sip

    def getSPort(self):
        return self.sport


if __name__ == "__main__":
    pass